<template>
  <view class="uni-pa-4 bg-white">
    <view>
      <uni-section title="手機號" type="line">
        <uni-easyinput class="uni-my-6" prefixIcon="phone" v-model="account.phone" placeholder="請輸入手機號"
          @iconClick="iconClick"></uni-easyinput>
      </uni-section>
      <view class="flex items-center justify-between uni-my-4">
        <uni-easyinput class="uni-mr-4" type="number" v-model="account.phoneCode" placeholder="請輸入手機驗證碼"></uni-easyinput>
        <button type="primary" size="mini">發送驗證碼</button>
      </view>
      <uni-section title="昵稱" type="line">
        <uni-easyinput class="uni-my-6" prefixIcon="person" v-model="account.name" placeholder="請輸入昵稱"
          @iconClick="iconClick"></uni-easyinput>
      </uni-section>
      <uni-section title="密碼" type="line">
        <uni-easyinput class="uni-my-6" type="password" v-model="account.password" placeholder="請輸入密碼"></uni-easyinput>
      </uni-section>
      <uni-section title="確認密碼" type="line">
        <uni-easyinput class="uni-my-6" type="password" v-model="account.repPassword"
          placeholder="請輸入重複密碼"></uni-easyinput>
      </uni-section>
      <button @click="register" class="uni-my-6">注冊</button>
    </view>
  </view>
</template>

<script>
import {
  httpUserRegister
} from '@/utils/api.js'
export default {
  data() {
    return {
      account: {
        name: '',
        phone: '',
        password: '',
        repPassword: '',
        phoneCode: ''
      }
    }
  },
  onLoad() {
    this.getMoble()
  },
  methods: {
    // 模拟获取手机号
    getMoble() {
      var prefixArray = new Array("130", "131", "132", "133", "135", "137", "138", "170", "187", "189");
      var i = parseInt(10 * Math.random());
      var prefix = prefixArray[i];
      for (var j = 0; j < 8; j++) {
        prefix = prefix + Math.floor(Math.random() * 10);
      }
      this.account.phone = prefix
    },
    async register() {
      if (this.account.password !== this.account.repPassword) {
        uni.showToast({
          title: '前後密碼不一致！',
          icon: 'none'
        })
        return false
      }
      const { code, data } = await httpUserRegister(this.account.phone, this.account.password, this.account.name)
      if (code === 200) {
        uni.setStorage({
          key: 'user_key',
          data: {
            userId: data.user.userId,
            name: data.user.name,
            phone: data.user.phone
          },
          success: () => {
            uni.showToast({
              title: '注冊成功',
              icon: 'none'
            })
            uni.$emit('getUserByApp')
            uni.reLaunch({
              url: '/pages/user/index'
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>